from plugin import plugin
from plugins import *
import ciao, plugins
import traceback, sys

__doc__ = "core"

class _core(plugin):
	"Core plugin module"
	
	def __init__(self):
		self._version = '3.0 stable'
	
	def __exec_all(self, method, args = None):
		mods = self._mods
		for mod in mods:
			if mod == 'core':	continue
			if hasattr(mods[mod], method):
				func = getattr(mods[mod], method)
				try:
					if args: func(args)
					else: func()
				except: traceback.print_exc(file=sys.stderr)
	
	@ignore_throw
	def _handle(self, msg):
		if msg['sender']['name'] == self._irc.nick:
			return
		self.__exec_all('_onMessage', msg)
		cmd, _, args = msg['data'].partition(' ')
		mods = self._mods
		for mod in mods:
			plugin = mods[mod]
			if msg['data'].startswith('.') and hasattr(plugin, cmd[1:]):
				func = getattr(plugin, cmd[1:])
				if func:
					try: func(msg, args)
					except: traceback.print_exc(file=sys.stderr)
	
	@ignore_throw
	def _onLoad(self):
		self.__exec_all('_onLoad')
	
	@ignore_throw
	def _onReload(self):
		self.__exec_all('_onReload')
	
	@ignore_throw
	def _onUnload(self):
		self.__exec_all('_onUnload')
	
	@plugins.irc_throw
	def version(self, msg, args):
		if args != '' and args in self._mods:
			mod = self._mods[args]
			if hasattr(mod, '_version'):
				return getattr(mod, '_version')
			else:
				return 'Unknown'
		return 'Ciao version: ' + ciao._version + '. IRC version: ' + self._irc._version
	
	def list(self, msg, args):
		"Usage: .list [admins, modules]"
		if args == 'admins':
			str = ', '.join(self._irc.admins)
			self._irc.reply(msg, 'Admins: ' + str)
		if args == 'plugins' or args == 'modules':
			str = ', '.join(self._mods)
			self._irc.reply(msg, 'Currently active modules: ' + str)
		if args == 'functions' or args == '':
			str = ', '.join(self._funcs)
			self._irc.reply(msg, 'Methods: ' + str)

	def whatis(self, msg, args):
		"Usage: .whatis [module name] (e.g. .whatis markov)"
		if len(args) == 0:
			self._irc.reply(msg, self.whatis.__doc__)
			return
		mods = self._mods
		if args not in mods:
			self._irc.reply(msg, 'Sorry, I dont know!')
			return
		doc = mods[args].__doc__
		if doc:
			self._irc.reply(msg, doc)
		else:
			self._irc.reply(msg, 'Sorry, no docs exist for that!')

	def help(self, msg, args):
		"Usage: .help [function name] (e.g. .help list)"
		if len(args) == 0:
			self._irc.reply(msg, self.help.__doc__)
			return
		if args in self._funcs:
			doc = self._funcs[args].__doc__
			if doc:
				self._irc.reply(msg, doc)
			else:
				self._irc.reply(msg, 'No documentation exists for that yet!')
		else:
			self._irc.reply(msg, 'Sorry I dont know what that is!')

